package com.oceansoft.mobile.biz.api.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;

/**
 * 事项中心接口
 * 
 * @time: 2014-6-18 0018 下午 14:14
 */
@Controller
@RequestMapping("api/matters")
public class ApiMattersController {

	/**
	 * 加载手机客户端可申报或预约事项字典，<br>
	 * 只有写字典项匹配的事项或警种才能在手机终端进行申报
	 * 
	 * @return Result
	 */
	@RequestMapping("dict/mobile/declare")
	public Result loadApplyDict() {
		HashMap<String, Object> dict = new HashMap<String, Object>(2) {
			{
				put("declare", new HashMap<String, String>() {
					{
						put("687a63ec-7e65-41e3-b90a-7febc72dc9a4", "matters-vehicle");// 货车临时通行证
						put("80d4c89e-69af-4978-aa1c-1d8c63d7f2e1", "matters-lawyer");// 律师预约
					}
				});
				put("appointment", new HashMap<String, String>() {
					{ // 预约警种
						put("2", "appointment-entry-exit");// 出入境
						put("3", "appointment-swat");// 特警
					}
				});
			}
		};
		return new Result(dict);
	}

	/**
	 * 加载事项中心
	 * 
	 * @return
	 */
	@RequestMapping(value = "index", method = GET)
	public String gotoMattersList(HttpServletRequest request, Model model) {
		String source = (String) request.getSession().getAttribute("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/matters/matter_center";
	}

	/**
	 * 查询事项详细信息
	 *
	 * @param deptType
	 *            部门类型 -1：市局 2：分局
	 * @param deptId
	 *            部门ID
	 * @param matterId
	 *            事项ID
	 * @return JSONP
	 */
	@RequestMapping(value = "detail/{dept_type}/{dept_id}/{matter_id}", method = GET)
	public String loadMatterDetail(@PathVariable("dept_type") int deptType, @PathVariable("dept_id") String deptId,
			@PathVariable("matter_id") String matterId, ModelMap model,HttpServletRequest request) {

		model.addAttribute("dept_type", deptType == -1 ? 1 : deptType);
		model.addAttribute("dept_id", deptId);
		model.addAttribute("matter_id", matterId);
		String source = (String) request.getSession().getAttribute("source");
	       if (!StringUtils.isEmpty(source)) {
	       	model.addAttribute("source", source);
	       }
		return "weixin/matters/matter_details";
	}

	/**
	 * 办件撤消
	 * 
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "product/undo", method = POST)
	public Result undoProject(@RequestParam(value = "Prjid") final String Prjid) throws IOException {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("Prjid", Prjid);
		String str = HttpClientUtil.doPost(Constant.host + "/api/matters/new/product/undo", params, "UTF-8");
		return JSONObject.parseObject(str, Result.class);
	}

	/**
	 * 满意度评价
	 * 
	 * @return Result
	 */
	@ResponseBody
	@RequestMapping(value = "product/myd")
	public Result projectMyd(@RequestParam(value = "prjid") final String prjid,
			@RequestParam(value = "type") final String type,
			@RequestParam(value = "mydcontent") final String mydcontent,
			@RequestParam(value = "mydtype") final String mydtype,
			@RequestParam(value = "createuserid") final String createuserid) throws IOException {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("prjid", prjid);
		params.put("type", type);
		params.put("mydtype", mydtype);
		params.put("mydcontent", mydcontent);
		params.put("createuserid", createuserid);
		String str = HttpClientUtil.doPost(Constant.host + "/api/matters/new/product/myd", params, "UTF-8");
		return JSONObject.parseObject(str, Result.class);
	}

	/**
	 * 自助移车
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "movecargabymy", method = POST)
	public Result moveCarByMyself(HttpServletRequest request, MultipartHttpServletRequest multRequest)
			throws IOException {
		CommonsMultipartFile file = (CommonsMultipartFile) multRequest.getFile("carfile");
		byte[] output = file.getBytes();
		String originalFileName = file.getOriginalFilename();
		String fileExtName = originalFileName.substring(originalFileName.lastIndexOf("."),originalFileName.length());
		String fileName = "movecar"+ new Date().getTime()+""+(100+(int)(Math.random()*900)) +fileExtName;
		//测试路径
//		String path = request.getRealPath("/static/upload/");
		//生产环境路径
		String path = Constant.SZGAWX_UPLOAD_PATH;
		FileOutputStream fos = new FileOutputStream(path+fileName);
		fos.write(output, 0, output.length);
		fos.close();

		final String imageUrl = "http://"+request.getHeader("host")+request.getContextPath()+"/static/upload/"+fileName;
		final String address = request.getParameter("address");
		final String tel = request.getParameter("tel");
		final String carNo = request.getParameter("carNo");
		final String carTypeId = request.getParameter("carTypeid");
//		final String cardNo = request.getParameter("cardNo");
		final String cardNo = "";

		String r = HttpClientUtil.doPost(Constant.host + "/api/movecar/movecarga", new HashMap<String, String>() {
			{
				put("imageUrl", imageUrl);
				put("address", address);
				put("tel", tel);
				put("carNo", carNo);
				put("carTypeId", carTypeId);
				put("cardNo", cardNo);
			}
		}, "UTF-8");
		JSONObject json = JSONObject.parseObject(r);
		Result re = new Result(Result.SUCC);
		re.setMsg("提交成功");
		// re.setData(json.get("data"));
		return re;

	}

	
	@ResponseBody
	@RequestMapping("details/{dept_type}/{dept_id}/{matter_id}")
	public Result unlockCompanyDetail(@PathVariable("dept_type")String dept_type,@PathVariable("dept_id")String dept_id,@PathVariable("matter_id")String matter_id) throws IOException {
		String url = Constant.host+"/api/matters/detail/"+dept_type+"/"+dept_id+"/"+matter_id;
        Result r = null;
        if(CacheBaseService.getInstance().exists(url))
        {
        	 r = CacheBaseService.getInstance().getObject(url, Result.class);
        }
        else
        { 
        	r = HttpClientUtil.doGAGet(url);
        	CacheBaseService.getInstance().cache(url, r, 1f);
        }
		return r;
	}
}
